package com.bbx.taxi.client.Activity.Address;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.InjectView;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.bbx.androidapi.util.SharedPreUtil;
import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.sdk.model.comm.returns.line.To_Cities;
import com.bbx.api.sdk.model.passanger.SvconfigBuild;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.sdk.net.config.conn.GetLineNet;
import com.bbx.taxi.client.Task.BaseAsyncTask;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.MyApplication.OnLocationResultListener;
import com.bbx.taxi.official.R;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Adapter.Chat.SearchCityAdapter;
import com.bbx.taxi.client.Adapter.City.CityAdapter;
import com.bbx.taxi.client.Bean.City;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Attribute.MainAttribute;
import com.bbx.taxi.client.Bean.Extra.AddressMsg;
import com.bbx.taxi.client.DB.CityDB;
import com.bbx.taxi.client.DB.LineDB;
import com.bbx.taxi.client.Task.MyLineTask;
import com.bbx.taxi.client.Task.MyLineTask.OnLineFinishListener;
import com.bbx.taxi.client.Util.ToCity;
import com.bbx.taxi.client.widget.City.BladeView;
import com.bbx.taxi.client.widget.City.BladeView.OnItemClickListener;
import com.bbx.taxi.client.widget.City.PinnedHeaderListView;

public class SelectCityActivity extends BaseBBXActivity implements TextWatcher,
		OnClickListener, MyApplication.EventHandler ,OnLocationResultListener,OnLineFinishListener{
	public static final int SELECTCITY_RESULT_CODE=10;
	@InjectView(R.id.search_edit)EditText mSearchEditText;
	@InjectView(R.id.ib_clear_text)ImageButton mClearSearchBtn;
	@InjectView(R.id.city_content_container) View mCityContainer;
	@InjectView(R.id.search_content_container) View mSearchContainer;
	@InjectView(R.id.citys_list) PinnedHeaderListView mCityListView;
	@InjectView(R.id.citys_bladeview) BladeView mLetter;
	@InjectView(R.id.search_list) ListView mSearchListView;
	private List<City> mCities;
	private SearchCityAdapter mSearchCityAdapter;
	private CityAdapter mCityAdapter;
	// 首字母集
	private List<String> mSections;
	// 根据首字母存放数据
	private Map<String, List<City>> mMap;
	// 首字母位置集
	private List<Integer> mPositions;
	// 首字母对应的位置
	private Map<String, Integer> mIndexer;
	private CityDB mCityDB;
	private InputMethodManager mInputMethodManager;
	List<City> cityList=new ArrayList<City>();
	private LineDB db_line;// 线路数据库
	private int intentType;
	private String start_address_name="";
	private boolean isInCity=false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.pinnedheader_listview);
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setTitle(getString(R.string.title_city));
	}

	private void startActivity(City city) {
		Intent i = new Intent();
		i.putExtra("city", city);
		setResult(RESULT_OK, i);
		finish();
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// do nothing
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		mSearchCityAdapter = new SearchCityAdapter(SelectCityActivity.this,
				mCities);
		mSearchListView.setAdapter(mSearchCityAdapter);
		mSearchListView.setTextFilterEnabled(true);
		if (mCities.size() < 1 || TextUtils.isEmpty(s)) {
			mCityContainer.setVisibility(View.VISIBLE);
			mSearchContainer.setVisibility(View.INVISIBLE);
			mClearSearchBtn.setVisibility(View.GONE);
		} else {
			mClearSearchBtn.setVisibility(View.VISIBLE);
			mCityContainer.setVisibility(View.INVISIBLE);
			mSearchContainer.setVisibility(View.VISIBLE);
			mSearchCityAdapter.getFilter().filter(s);
		}
	}

	@Override
	public void afterTextChanged(Editable s) {
		// 如何搜索字符串长度为0，是否隐藏输入法
		// if(TextUtils.isEmpty(s)){
		// mInputMethodManager.hideSoftInputFromWindow(
		// mSearchEditText.getWindowToken(), 0);
		// }

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.ib_clear_text:
			if (!TextUtils.isEmpty(mSearchEditText.getText().toString())) {
				mSearchEditText.setText("");
				mInputMethodManager.hideSoftInputFromWindow(
						mSearchEditText.getWindowToken(), 0);
			}
			break;
		default:
			super.onClick(v);
			break;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mApplication.removeEventHandler(this);
	}

	@Override
	public void onCityComplite() {
		// 城市列表加载完的回调函数
		mCities = mApplication.getCityList();
		mSections = mApplication.getSections();
		mMap = mApplication.getMap();
		mPositions = mApplication.getPositions();
		mIndexer = mApplication.getIndexer();

		mCityAdapter = new CityAdapter(SelectCityActivity.this, mCities, mMap,
				mSections, mPositions);
//		mLetter.setVisibility(View.VISIBLE);【暂时隐藏】
		mCityListView.setAdapter(mCityAdapter);
		mCityListView.setOnScrollListener(mCityAdapter);
		mCityListView.setPinnedHeaderView(LayoutInflater.from(
				SelectCityActivity.this).inflate(
				R.layout.biz_plugin_weather_list_group_item, mCityListView,
				false));
		// mActionBar.setProgressBarVisibility(View.INVISIBLE);
	}

	@Override
	public void onNetChange() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationResult(BDLocation location) {
//		location_city.setText(mApplication.loctionCity+"("+mApplication.loctionType+")");
//		location_city.setText(mApplication.loctionCity!=null?mApplication.loctionCity:getString(R.string.loctionType_no));
	}
	public void onLocationResult(ReverseGeoCodeResult result) {
//		location_city.setText(mApplication.loctionCity+"("+mApplication.loctionType+")");
//		location_city.setText(result.getAddressDetail().city!=null?result.getAddressDetail().city:getString(R.string.loctionType_no));
	}
	@Override
	public void onLocationFail(boolean isnet) {
		// TODO Auto-generated method stub
		
	}
	@Override
	protected void initView() {
		Intent intent = getIntent();
		isInCity= intent.getExtras().getBoolean(AddressMsg.extra_incity);
		mApplication.setEventHandler(this);
		db_line=new LineDB(this);
		if(mApplication.loctionCity==null||mApplication.loctionCity.equals("")||mApplication.loctionType.equals("")){
//			location_city.setText(getString(R.string.loctionType_no));
			mApplication.setOnLocationResultListener(this);
			mApplication.onStartLocation();
		}
		else{
//			location_city.setText(mApplication.loctionCity+"("+mApplication.loctionType+")");
//			location_city.setText(mApplication.loctionCity!=null?mApplication.loctionCity:getString(R.string.loctionType_no));

		}
		mSearchEditText.addTextChangedListener(this);
		mClearSearchBtn.setOnClickListener(this);
		mCityListView.setEmptyView(findViewById(R.id.tv_nocity));
		mLetter.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(String s) {
				if (mIndexer.get(s) != null) {
					mCityListView.setSelection(mIndexer.get(s));
				}
			}
		});
		mLetter.setVisibility(View.GONE);
		mSearchListView.setEmptyView(findViewById(R.id.search_empty));
		mSearchContainer.setVisibility(View.GONE);
		mSearchListView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				mInputMethodManager.hideSoftInputFromWindow(
						mSearchEditText.getWindowToken(), 0);
				return false;
			}
		});
		mCityListView
				.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						// TODO Auto-generated method stub
//						Toast.makeText(SelectCityActivity.this,
//								mCityAdapter.getItem(position).getCity(),
//								Toast.LENGTH_LONG).show();
						Bundle bundle=new Bundle();
						bundle.putString(AddressMsg.extra_is_detail,mCityAdapter.getItem(position).getIs_detail());
			    		bundle.putString(AddressMsg.extra_city,mCityAdapter.getItem(position).getCity());
			    		Intent intent=new Intent();
			    		intent.putExtras(bundle);
			    		setResult(MainAttribute.REQUEST_CODE_PERSON,intent);   
			    		finish();
			    		overridePendingTransition(0, R.anim.base_slide_right_out);
					}
				});

		mSearchListView
				.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						// TODO Auto-generated method stub
						Toast.makeText(SelectCityActivity.this,
								mSearchCityAdapter.getItem(position).getCity(),
								Toast.LENGTH_LONG).show();
						Bundle bundle=new Bundle();
						bundle.putString(AddressMsg.extra_is_detail,mCityAdapter.getItem(position).getIs_detail());
			    		bundle.putString(AddressMsg.extra_city,mCityAdapter.getItem(position).getCity());
			    		Intent intent=new Intent();
			    		intent.putExtras(bundle);
			    		setResult(MainAttribute.REQUEST_CODE_PERSON,intent);   
			    		finish();
			    		overridePendingTransition(0, R.anim.base_slide_right_out);
					}
				});
		intentType = intent.getExtras().getInt(AddressMsg.extra_editaddress);
		start_address_name = intent.getExtras().getString(AddressMsg.extra_address_name);
	}

	@Override
	protected void initData() {
		mCityDB = mApplication.getCityDB();
		mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		if(isInCity){
			ToCity.setInCityList(this);
		}
		else{
         //城市列表有数据
		if (mApplication.isCityListComplite()) {
			mCities = mApplication.getCityList();
			mSections = mApplication.getSections();
			mMap = mApplication.getMap();
			mPositions = mApplication.getPositions();
			mIndexer = mApplication.getIndexer();

			mCityAdapter = new CityAdapter(SelectCityActivity.this, mCities,
					mMap, mSections, mPositions);
			mCityListView.setAdapter(mCityAdapter);
			mCityListView.setOnScrollListener(mCityAdapter);
			mCityListView.setPinnedHeaderView(LayoutInflater.from(
					SelectCityActivity.this).inflate(
					R.layout.biz_plugin_weather_list_group_item, mCityListView,
					false));
		
//			mLetter.setVisibility(View.VISIBLE);【暂时隐藏】

		}
		else{
			mCities=new ArrayList<City>();
			mCities.clear();
			mCityAdapter = new CityAdapter(SelectCityActivity.this, mCities,
					mMap, mSections, mPositions);
			mCityListView.setAdapter(mCityAdapter);
			getOnLine();
//			mCityListView.setEmptyView(null);
//			findViewById(R.id.citys_list_empty).setVisibility(View.GONE);
		 }
		}
	}

	@Override
	protected void desotryItems() {
		// TODO Auto-generated method stub
		
	}
	/**
	 * 获取线路
	 */
	private void getOnLine() {
		if(loaddialog!=null&&!loaddialog.isShowing()){
			loaddialog.show();
		}
		MyLineTask.getInstance(context).setOnLineFinishListener(this);	
	}
	@Override
	public void onLineFinish(boolean isisSuccess) {
		if(loaddialog!=null){
			loaddialog.onDismiss();
		}
		if(isisSuccess){
		switch (intentType) {
		case AddressMsg.ADDRESS_START_MAIN:
		case AddressMsg.ADDRESS_START_CHANGE:
			ToCity.setCityList(context);
			break;
		case AddressMsg.ADDRESS_END_MAIN:
		case AddressMsg.ADDRESS_END_CHANGE:
			if (start_address_name.equals("")) {
				ToCity.setCityList(context);
			}
			else{
				ToCity.setToCityList(context, start_address_name);	
			}
		
			break;
		}
		}else{
			ToastUtil.showToast(context, R.string.no_network);
		}
	}
	
}
